package colin.project.sso.server.common.event.aspect;

import org.aspectj.lang.JoinPoint;
import org.springframework.util.ReflectionUtils;

import java.lang.reflect.Method;

/**
 * @Author joker
 * @Title BasicAspect
 * @Description
 * @Date 2019/5/20 12:08 PM
 * @Since
 * @Version 1.0.0
 */
public class BasicAspect {

    /**
     * 获取代理类
     *
     * @param jp
     * @return
     */
    public Class getProxyClass(JoinPoint jp) {
        return jp.getTarget().getClass();
    }

    /**
     * 获取代理方法
     *
     * @return
     */
    public Method getProxyMethod(JoinPoint jp) {
        //获取代理目标
        Class targetClass = getProxyClass(jp);
        //获取当前访问方法名
        String methodName = jp.getSignature().getName();
        //获取访问方法的携带参数
        Object[] args = jp.getArgs();
        Method targetMethod = null;
        if (null == args || args.length == 0) {
            targetMethod = ReflectionUtils.findMethod(targetClass, methodName);
        } else {
            Class[] argClasses = new Class[args.length];
            for (int i = 0; i < args.length; i++) {
                argClasses[i] = args[i].getClass();
            }
            targetMethod = ReflectionUtils.findMethod(targetClass, methodName, argClasses);
        }
        return targetMethod;
    }

    /**
     * 是否存在指定方法名的方法
     *
     * @param methodName
     * @return
     */
    public boolean existsTargetMethod(JoinPoint jp, String methodName) {
        //获取代理目标
        Class targetClass = getProxyClass(jp);
        Method targetMethod = ReflectionUtils.findMethod(targetClass, methodName);
        if (targetMethod == null) {
            return false;
        }
        return true;
    }
}
